# -*- coding: utf-8 -*-
"""
@Author: thekernel
@Date: 2020/5/22 08:21
@Description: 通过 selenium 自动登录 豆瓣
"""
from selenium import webdriver
from fake_useragent import UserAgent
import time
import random
import requests


def login(browser):
    url = "https://www.douban.com/"
    username = "17342019665"
    password = "Kernel990621"

    # 跳转到 密码登录
    firefox.switch_to.frame(firefox.find_element_by_tag_name("iframe"))  # 切换到指定 iframe
    login_page = browser.find_element_by_xpath("/html/body/div[1]/div[1]/ul[1]/li[2]")
    login_page.click()
    time.sleep(3+random.random())

    username_input = browser.find_element_by_xpath("//*[@id=\"username\"]")
    username_input.send_keys(username)
    password_input = browser.find_element_by_xpath("//*[@id=\"password\"]")
    password_input.send_keys(password)
    login_button = browser.find_element_by_xpath("/html/body/div[1]/div[2]/div[1]/div[5]/a")
    login_button.click()
    time.sleep(3+random.random())

    cookies = browser.get_cookies()
    cookie_dict = dict()
    for item in cookies:
        cookie_dict[item["name"]] = item["value"]

    response = requests.get(url, cookies=cookie_dict)
    print(response.text)


if __name__ == '__main__':
    url = "https://www.douban.com/"

    firefox_driver = "/Users/thekernel/Code/PythonWorkspace/PythonLib/geckodriver"
    options = webdriver.FirefoxOptions()
    # options.add_argument("--headless")
    options.add_argument("user-agent=" + UserAgent().random)
    firefox = webdriver.Firefox(options=options, executable_path=firefox_driver)

    firefox.get(url)
    time.sleep(3+random.random())

    login(firefox)
